package com.ls.fw.imgserver.handler;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ls.fw.commons.core.utils.RandUtil;
import com.ls.fw.commons.core.utils.ResourcePathUtil;
import com.ls.fw.commons.core.utils.file.FileUtil;
import com.ls.fw.imgserver.enums.OperatType;
import com.ls.fw.imgserver.exception.ImageOperateException;
import com.ls.fw.imgserver.exception.ImageParaException;
import com.ls.fw.imgserver.util.PathUtil;
import com.ls.fw.web.core.servlet.BaseServlet.SubmitType;
import com.ls.fw.web.core.servlet.bean.AjaxResult;
import com.ls.fw.web.core.servlet.utils.ObjectUtil;

public class RequestHandlerImpl implements RequestHandler{
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	public static final String DEFALUT_PATH = "etc/resources/opencv";
	public static final String OPERATTYPE = "command";
	public static final String DEST_PARA = "dest";
	private String contextDir  = "";//项目路径D://tomcat/webapps/fw_imgServer
	private String baseDir  = "";//保存文件的根目录，如D://tomcat/test/resources/images
	private boolean isAbsolutePath  = false;
//	private ImageHandler im = new ImageHandlerImpl(ResourcePathUtil.getClassAbsoutlePath(DEFALUT_PATH));

	public RequestHandlerImpl(String contextDir, String baseDir) {
	    this(contextDir,baseDir,false);
	}
	
	public RequestHandlerImpl(String contextDir, String baseDir,
			boolean isAbsolutePath) {
		super();
		this.setContextDir(contextDir);
		this.baseDir = baseDir;
		this.isAbsolutePath = isAbsolutePath;
	}



	public void handl(SubmitType submitType,
			HttpServletRequest request, HttpServletResponse response) throws ImageOperateException, ServletException, IOException{
		String type = request.getParameter(OPERATTYPE);
		OperatType oper_type = OperatType.typeOf(type);
		if(oper_type!=null){
			switch(oper_type){
				case CUT:
					this.cut(request, response);
					break;
				case DEL:
					this.del(request, response);
					break;
				case RENAME:
					this.rename(request, response);
					break;
				case RESIZE:
					this.resize(request, response);
					break;
				case SCALE:
					this.scale(request, response);
					break;
				case ROTATE:
					this.rotate(request, response);
					break;
				case SHOW:
					this.show(request, response);
					break;
				case WATERMARK:
					this.watermark(request, response);
					break;
				case MOVE:
					this.move(request, response);
					break;
				case COPY:
					this.copy(request, response);
					break;
				case FORMAT:
					this.format(request, response);
					break;
				case UPLOAD:
					this.upload(request, response);
					break;
				case DOWNLOAD:
					this.down(request, response);
					break;
				case DETECT:
					this.detect(request, response);
					break;
				default:
					break;
			}
		}else{
			throw new ImageOperateException("不支持该操作类型["+type+"]");
		}
	}

	@Override
	public void cut(HttpServletRequest request, HttpServletResponse response)
			throws ImageOperateException {
		//String url = PathUtil.getParameter(request,"url");
		String path = PathUtil.getPath(request, this.baseDir);
		String status_msg ="剪切成功！"; 
		boolean success =  false;
		String destpath = PathUtil.getPath(request, this.baseDir,"dest");
		String newPath = PathUtil.getPathPara(request);
		if(!ObjectUtil.isEmpty(path)){
			try {
				boolean hasDestPath = false;
				if(ObjectUtil.isNotEmpty(destpath)){
					File pfileDir = new File(destpath);
					if(pfileDir.exists()){
						throw new ImageParaException("保存路径文件已存在，请重新设置保存目标文件！");
					}else{
						if(!pfileDir.getParentFile().exists()){
							pfileDir.getParentFile().mkdirs();
						}
						hasDestPath = true;
					}
				}
				File file = new File(path);
				if(file.exists()){
					String name ="";
					if(!hasDestPath){
						name = FileUtil.getFileNameWithoutExtension(file.getName())+"_cut_"+RandUtil.genDateYYYYMMDDHHmmName()+FileUtil.getExt(file.getName());
						name = FileUtil.getFinalFileName(file.getParent(), name);
						destpath =  file.getParent() + File.separator + name;
					}
					int x = PathUtil.getIntParameter(request, "x");
					int y = PathUtil.getIntParameter(request, "y");
					int w = PathUtil.getIntParameter(request, "w");
					int h = PathUtil.getIntParameter(request, "h");
					Thumbnails.of(path).sourceRegion(x, y, w, h).size(
						w, h).keepAspectRatio(false).toFile(destpath);
					int delsrc = PathUtil.getIntParameter(request, "delsrc");
					if(delsrc==1){
						FileUtil.delete(file);
					}
					if(hasDestPath){
						newPath = PathUtil.getPathPara(request,"dest");
					}else{
						newPath = StringUtils.replace(newPath, file.getName(), name);
					}
					success = true;
				}else{
					status_msg ="剪切失败，源文件不存在！"; 
				}
			} catch (Exception e) {
				e.printStackTrace();
				status_msg = e.getMessage();
			}
		}else{
		   status_msg ="剪切失败，目标路径不正确！"; 
		}
		Map<String,Object> map = new HashMap<String,Object>(3);
		map.put(STATUS_CODE, success?AjaxResult.SUCCESS:AjaxResult.FAIL);
		map.put(MSG, status_msg);
		map.put(RESULT, newPath);
		String msg = this.sendJSONObject(response,map);
		this.logger.debug("将文件["+path+"]剪切到["+destpath+"]:"+status_msg+":"+msg);
	}

	@Override
	public void del(HttpServletRequest request, HttpServletResponse response)
			throws ImageOperateException {
		String path = PathUtil.getPath(request, this.baseDir);
		Map<String,Object> map = new HashMap<String,Object>(2);
		String status_msg = "成功";
		try {
			if(FileUtil.delete(path)){
				map.put(STATUS_CODE, AjaxResult.SUCCESS);
				map.put(MSG, "删除"+status_msg+"!");
			}else{
				status_msg = "失败";
				map.put(STATUS_CODE, AjaxResult.FAIL);
				map.put(MSG, "删除"+status_msg+"!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put(STATUS_CODE, AjaxResult.FAIL);
			map.put(MSG, e.getMessage());
		}
		String msg = this.sendJSONObject(response,map);
		this.logger.debug("删除["+path+"]"+status_msg+":"+msg);
		
	}

	@Override
	public void rename(HttpServletRequest request, HttpServletResponse response)
			throws ImageOperateException {
		String path = PathUtil.getPath(request, this.baseDir);
		String newname = PathUtil.getParameter(request, "newname");
		Map<String,Object> map = new HashMap<String,Object>(3);
		String status_msg ="重命名成功！"; 
		boolean  success = false;
		String newPath = PathUtil.getPathPara(request);
		try {
			File file = new File(path);
			if(!ObjectUtil.isEmpty(path) && file.exists()){
				String parent = file.getParent();
				String ext = FileUtil.getFileExtension(newname);
				if(ObjectUtil.isEmpty(ext)){
					newname = newname + FileUtil.getExt(file.getName());
				}
				File pfile = new File(parent+File.separator+newname);
				if(!pfile.exists()){
					file.renameTo(pfile);
					newPath = StringUtils.replace(newPath, file.getName(), pfile.getName());
					success = true;
				}else{
					status_msg ="重命名失败，目标文件已存在，请重新命名！"; 
				}
			}else{
				status_msg ="重命名失败，源文件不存在！"; 
			}
		} catch (Exception e) {
			e.printStackTrace();
			status_msg = e.getMessage() ;
		}
		map.put(STATUS_CODE, success?AjaxResult.SUCCESS:AjaxResult.FAIL);
		map.put(MSG, status_msg);
		map.put(RESULT, newPath);
		String msg = this.sendJSONObject(response,map);
		this.logger.debug("将文件["+path+"]重命名为["+newname+"]:"+status_msg+":"+msg);
	}

	public void scale(HttpServletRequest request, HttpServletResponse response)throws ImageOperateException{
		String path = PathUtil.getPath(request, this.baseDir);
		String status_msg ="按比例缩放成功！"; 
		boolean success =  false;
		String destpath = PathUtil.getPath(request, this.baseDir,"dest");
		String newPath = PathUtil.getPathPara(request);
		if(!ObjectUtil.isEmpty(path)){
			try {
				boolean hasDestPath = false;
				if(ObjectUtil.isNotEmpty(destpath)){
					File pfileDir = new File(destpath);
					if(pfileDir.exists()){
						throw new ImageParaException("保存路径文件已存在，请重新设置保存目标文件！");
					}else{
						if(!pfileDir.getParentFile().exists()){
							pfileDir.getParentFile().mkdirs();
						}
						hasDestPath = true;
					}
				}
				File file = new File(path);
				if(file.exists()){
					String name ="";
					if(!hasDestPath){
						name = FileUtil.getFileNameWithoutExtension(file.getName())+"_scale_"+RandUtil.genDateYYYYMMDDHHmmName()+FileUtil.getExt(file.getName());
						name = FileUtil.getFinalFileName(file.getParent(), name);
						destpath =  file.getParent() + File.separator + name;
					}
					double scale = PathUtil.getDoubleParameter(request, "scale");
					double w = PathUtil.getDoubleParameter(request, "w");
					double h = PathUtil.getDoubleParameter(request, "h");
					Thumbnails.of(path).scale(scale).scale(w, h).toFile(
							destpath);
					int delsrc = PathUtil.getIntParameter(request, "delsrc");
					if(delsrc==1){
						FileUtil.delete(file);
					}
					if(hasDestPath){
						newPath = PathUtil.getPathPara(request,"dest");
					}else{
						newPath = StringUtils.replace(newPath, file.getName(), name);
					}
					success = true;
				}else{
					status_msg ="按比例缩放失败，源文件不存在！"; 
				}
			} catch (Exception e) {
				e.printStackTrace();
				status_msg = e.getMessage();
			}
		}else{
		   status_msg ="按比例缩放失败，目标路径不正确！"; 
		}
		Map<String,Object> map = new HashMap<String,Object>(3);
		map.put(STATUS_CODE, success?AjaxResult.SUCCESS:AjaxResult.FAIL);
		map.put(MSG, status_msg);
		map.put(RESULT, newPath);
		String msg = this.sendJSONObject(response,map);
		this.logger.debug("将文件["+path+"]按比例缩放到["+destpath+"]:"+status_msg+":"+msg);
	}
	
	@Override
	public void resize(HttpServletRequest request, HttpServletResponse response)
			throws ImageOperateException {
		String path = PathUtil.getPath(request, this.baseDir);
		String status_msg ="缩放成功！"; 
		boolean success =  false;
		String destpath = PathUtil.getPath(request, this.baseDir,"dest");
		String newPath = PathUtil.getPathPara(request);
		if(!ObjectUtil.isEmpty(path)){
			try {
				boolean hasDestPath = false;
				if(ObjectUtil.isNotEmpty(destpath)){
					File pfileDir = new File(destpath);
					if(pfileDir.exists()){
						throw new ImageParaException("保存路径文件已存在，请重新设置保存目标文件！");
					}else{
						if(!pfileDir.getParentFile().exists()){
							pfileDir.getParentFile().mkdirs();
						}
						hasDestPath = true;
					}
				}
				File file = new File(path);
				if(file.exists()){
					String name ="";
					if(!hasDestPath){
						name = FileUtil.getFileNameWithoutExtension(file.getName())+"_resize_"+RandUtil.genDateYYYYMMDDHHmmName()+FileUtil.getExt(file.getName());
						name = FileUtil.getFinalFileName(file.getParent(), name);
						destpath =  file.getParent() + File.separator + name;
					}
					int w = PathUtil.getIntParameter(request, "w");
					int h = PathUtil.getIntParameter(request, "h");
					boolean  keepAspectRatio = PathUtil.getBooleanParameter(request, "keepAspectRatio", true);
					Thumbnails.of(path).size( w, h).keepAspectRatio(keepAspectRatio).toFile(
							destpath);
					int delsrc = PathUtil.getIntParameter(request, "delsrc");
					if(delsrc==1){
						FileUtil.delete(file);
					}
					if(hasDestPath){
						newPath = PathUtil.getPathPara(request,"dest");
					}else{
						newPath = StringUtils.replace(newPath, file.getName(), name);
					}
					success = true;
				}else{
					status_msg ="缩放失败，源文件不存在！"; 
				}
			} catch (Exception e) {
				e.printStackTrace();
				status_msg = e.getMessage();
			}
		}else{
		   status_msg ="缩放失败，目标路径不正确！"; 
		}
		Map<String,Object> map = new HashMap<String,Object>(3);
		map.put(STATUS_CODE, success?AjaxResult.SUCCESS:AjaxResult.FAIL);
		map.put(MSG, status_msg);
		map.put(RESULT, newPath);
		String msg = this.sendJSONObject(response,map);
		this.logger.debug("将文件["+path+"]缩放到["+destpath+"]:"+status_msg+":"+msg);
	}

	@Override
	public void rotate(HttpServletRequest request, HttpServletResponse response)
			throws ImageOperateException {
		String path = PathUtil.getPath(request, this.baseDir);
		String status_msg ="旋转成功！"; 
		boolean success =  false;
		String destpath = PathUtil.getPath(request, this.baseDir,"dest");
		String newPath = PathUtil.getPathPara(request);
		if(!ObjectUtil.isEmpty(path)){
			try {
				boolean hasDestPath = false;
				if(ObjectUtil.isNotEmpty(destpath)){
					File pfileDir = new File(destpath);
					if(pfileDir.exists()){
						throw new ImageParaException("保存路径文件已存在，请重新设置保存目标文件！");
					}else{
						if(!pfileDir.getParentFile().exists()){
							pfileDir.getParentFile().mkdirs();
						}
						hasDestPath = true;
					}
				}
				File file = new File(path);
				if(file.exists()){
					String name ="";
					if(!hasDestPath){
						name = FileUtil.getFileNameWithoutExtension(file.getName())+"_rotate_"+RandUtil.genDateYYYYMMDDHHmmName()+FileUtil.getExt(file.getName());
						name = FileUtil.getFinalFileName(file.getParent(), name);
						destpath =  file.getParent() + File.separator + name;
					}
					int w = PathUtil.getIntParameter(request, "w");
					int h = PathUtil.getIntParameter(request, "h");
					double rotate = PathUtil.getDoubleParameter(request, "rotate");
					boolean  keepAspectRatio = PathUtil.getBooleanParameter(request, "keepAspectRatio", true);
					if(h>0&&w>0){
						Thumbnails.of(path).size( w, h).keepAspectRatio(keepAspectRatio).rotate(rotate).toFile(
								destpath);
					}else{
						Thumbnails.of(path).rotate(rotate).toFile(
								destpath);
					}
					
					int delsrc = PathUtil.getIntParameter(request, "delsrc");
					if(delsrc==1){
						FileUtil.delete(file);
					}
					if(hasDestPath){
						newPath = PathUtil.getPathPara(request,"dest");
					}else{
						newPath = StringUtils.replace(newPath, file.getName(), name);
					}
					success = true;
				}else{
					status_msg ="旋转失败，源文件不存在！"; 
				}
			} catch (Exception e) {
				e.printStackTrace();
				status_msg = e.getMessage();
			}
		}else{
		   status_msg ="旋转失败，目标路径不正确！"; 
		}
		Map<String,Object> map = new HashMap<String,Object>(3);
		map.put(STATUS_CODE, success?AjaxResult.SUCCESS:AjaxResult.FAIL);
		map.put(MSG, status_msg);
		map.put(RESULT, newPath);
		String msg = this.sendJSONObject(response,map);
		this.logger.debug("将文件["+path+"]旋转到["+destpath+"]:"+status_msg+":"+msg);
	}

	@Override
	public void show(HttpServletRequest request, HttpServletResponse response)
			throws ImageOperateException, ServletException, IOException {
		request.getRequestDispatcher("/getImg").forward(request, response);
	}

	@Override
	public void watermark(HttpServletRequest request,
			HttpServletResponse response) throws ImageOperateException {
		//watermark(位置，水印图，透明度)
		String path = PathUtil.getPath(request, this.baseDir);
		String waterpath = PathUtil.getPath(request, this.baseDir,"water");
		String status_msg ="添加水印成功！"; 
		boolean success =  false;
		String destpath = PathUtil.getPath(request, this.baseDir,"dest");
		String newPath = PathUtil.getPathPara(request);
		if(!ObjectUtil.isEmpty(path)){
			try {
				if(!ObjectUtil.isEmpty(waterpath)){
					File file = new File(waterpath);
					if(!file.exists()){
						throw new ImageParaException("添加水印失败,请设置水印图片路径！");
					}
				}else{
					throw new ImageParaException("添加水印失败,请设置水印图片路径！");
				}
				boolean hasDestPath = false;
				if(ObjectUtil.isNotEmpty(destpath)){
					File pfileDir = new File(destpath);
					if(pfileDir.exists()){
						throw new ImageParaException("保存路径文件已存在，请重新设置保存目标文件！");
					}else{
						if(!pfileDir.getParentFile().exists()){
							pfileDir.getParentFile().mkdirs();
						}
						hasDestPath = true;
					}
				}
				File file = new File(path);
				if(file.exists()){
					String name ="";
					if(!hasDestPath){
						name = FileUtil.getFileNameWithoutExtension(file.getName())+"_watermark_"+RandUtil.genDateYYYYMMDDHHmmName()+FileUtil.getExt(file.getName());
						name = FileUtil.getFinalFileName(file.getParent(), name);
						destpath =  file.getParent() + File.separator + name;
					}
					String position = PathUtil.getParameter(request, "position");
					int w = PathUtil.getIntParameter(request, "w");
					int h = PathUtil.getIntParameter(request, "h");
					
					float opacity = PathUtil.getFloatParameter(request, "opacity",0.5F);
					
					float quality = PathUtil.getFloatParameter(request, "quality",1F);
					Position pos = Positions.BOTTOM_LEFT;
					if(ObjectUtil.isNotEmpty(position)){
						pos = Positions.valueOf(position);
						if(pos==null){
							pos = Positions.BOTTOM_LEFT;
						}
					}
					if(h>0 && w>0){
						Thumbnails.of(path).size(w, h).watermark(
								pos,
								ImageIO.read(new File(waterpath)), opacity)
								.outputQuality(quality).toFile(destpath);

					}else{
						Thumbnails.of(path).watermark(
								pos,
								ImageIO.read(new File(waterpath)), opacity)
								.outputQuality(quality).toFile(destpath);
					}
					
					int delsrc = PathUtil.getIntParameter(request, "delsrc");
					if(delsrc==1){
						FileUtil.delete(file);
					}
					if(hasDestPath){
						newPath = PathUtil.getPathPara(request,"dest");
					}else{
						newPath = StringUtils.replace(newPath, file.getName(), name);
					}
					success = true;
				}else{
					status_msg ="添加水印失败，源文件不存在！"; 
				}
			} catch (Exception e) {
				e.printStackTrace();
				status_msg = e.getMessage();
			}
		}else{
			status_msg ="添加水印失败，目标路径不正确！"; 
		}
		Map<String,Object> map = new HashMap<String,Object>(3);
		map.put(STATUS_CODE, success?AjaxResult.SUCCESS:AjaxResult.FAIL);
		map.put(MSG, status_msg);
		map.put(RESULT, newPath);
		String msg = this.sendJSONObject(response,map);
		this.logger.debug("将文件["+path+"]添加水印到["+destpath+"]:"+status_msg+":"+msg);
	}
	
	
	@Override
	public void move(HttpServletRequest request, HttpServletResponse response)
			throws ImageOperateException {
		String path = PathUtil.getPath(request, this.baseDir);
		String destpath = PathUtil.getPath(request,this.baseDir,DEST_PARA);
		Map<String,Object> map = new HashMap<String,Object>(3);
		String status_msg = "移动成功！"; 
		boolean success =  false;
		String newPath = PathUtil.getPathPara(request);
		try {
			File file = new File(path);
			if(!ObjectUtil.isEmpty(destpath)){
				if(file.exists()){
					File pfile = new File(destpath);
					String parent = pfile.getParent();
					File pfileDir = new File(parent);
					if(!pfileDir.exists()){
						pfileDir.mkdirs();
					}
					if(!pfile.exists()){
						file.renameTo(pfile);
						newPath = PathUtil.getPathPara(request,DEST_PARA);
						success = true;
					}else{
						status_msg ="移动失败，目标文件已存在，请重新设置目标文件！"; 
					}
				}else{
					status_msg ="移动失败，源文件不存在！"; 
				}
			}else{
				status_msg ="移动失败，目标路径不正确！"; 
			}
		} catch (Exception e) {
			e.printStackTrace();
			status_msg = e.getMessage() ;
		}
		
		map.put(STATUS_CODE, success?AjaxResult.SUCCESS:AjaxResult.FAIL);
		map.put(MSG, status_msg);
		map.put(RESULT, newPath);
		String msg = this.sendJSONObject(response,map);
		this.logger.debug("将文件["+path+"]移动到["+destpath+"]:"+status_msg+":"+msg);
		
	}
	
	public void copy(HttpServletRequest request, HttpServletResponse response)throws ImageOperateException{
		String path = PathUtil.getPath(request, this.baseDir);
		String destpath = PathUtil.getPath(request,this.baseDir,DEST_PARA);
		Map<String,Object> map = new HashMap<String,Object>(3);
		String status_msg ="复制成功！"; 
		boolean success =  false;
		String newPath = PathUtil.getPathPara(request);
		try {
			File file = new File(path);
			if(!ObjectUtil.isEmpty(destpath)){
				if(file.exists()){
					File pfile = new File(destpath);
					String parent = pfile.getParent();
					File pfileDir = new File(parent);
					if(!pfileDir.exists()){
						pfileDir.mkdirs();
					}
					if(!pfile.exists()){
						success = FileUtil.copy(file, pfile);
						int delsrc = PathUtil.getIntParameter(request, "delsrc");
						if(delsrc==1){
							FileUtil.delete(file);
						}
						newPath = PathUtil.getPathPara(request,DEST_PARA);
					}else{
						status_msg ="复制失败，目标文件已存在，请重新设置目标文件！"; 
					}
				}else{
					status_msg ="复制失败，源文件不存在！"; 
				}
			}else{
				status_msg ="复制失败，目标路径不正确！"; 
			}
		} catch (Exception e) {
			e.printStackTrace();
			status_msg = e.getMessage() ;
		}
		
		map.put(STATUS_CODE, success?AjaxResult.SUCCESS:AjaxResult.FAIL);
		map.put(MSG, status_msg);
		map.put(RESULT, newPath);
		String msg = this.sendJSONObject(response,map);
		this.logger.debug("将文件["+path+"]复制到["+destpath+"]:"+status_msg+":"+msg);
	
	}
	
	public void format(HttpServletRequest request, HttpServletResponse response)throws ImageOperateException{
		String path = PathUtil.getPath(request, this.baseDir);
		String format = PathUtil.getParameter(request, "format");
		Map<String,Object> map = new HashMap<String,Object>(3);
		String status_msg ="转化图像格式成功！"; 
		boolean  success = false;
		String destpath = PathUtil.getPath(request, this.baseDir,"dest");
		String newPath = PathUtil.getPathPara(request);
		if(!ObjectUtil.isEmpty(format)){
			try {
				File file = new File(path);
				if(!ObjectUtil.isEmpty(path) && file.exists()){
					boolean hasDestPath = false;
					boolean changeExt = false;
					if(ObjectUtil.isNotEmpty(destpath)){
						File pfile = new File(destpath);
						String ext = FileUtil.getFileExtension(pfile.getName());
						if(ObjectUtil.isNotEmpty(ext)){
							if(!ext.equalsIgnoreCase(format)){
								destpath = pfile.getParent()+File.separator+FileUtil.getFileNameWithoutExtension(pfile.getName())+"."+format;
								changeExt = true;
							}
						}
						if(changeExt){
							pfile = new File(destpath);
						}
						if(pfile.exists()){
							throw new ImageParaException("保存路径文件已存在，请重新设置保存目标文件！");
						}else{
							if(!pfile.getParentFile().exists()){
								pfile.getParentFile().mkdirs();
							}
							hasDestPath = true;
						}
					}
					String name ="";
					if(!hasDestPath){
						name = FileUtil.getFileNameWithoutExtension(file.getName())+"_format_"+RandUtil.genDateYYYYMMDDHHmmName()+"."+format;
						name = FileUtil.getFinalFileName(file.getParent(), name);
						destpath =  file.getParent() + File.separator + name;
					}	
					Thumbnails.of(path).scale(1.0D).outputFormat(format)
					.toFile(destpath);
					int delsrc = PathUtil.getIntParameter(request, "delsrc");
					if(delsrc==1){
						FileUtil.delete(file);
					}
					if(hasDestPath){
						newPath = PathUtil.getPathPara(request,"dest");
						if(changeExt){
							newPath = FileUtil.getParentPath(newPath)+File.separator+FileUtil.getFileNameWithoutExtension(newPath)+"."+format;
						}
					}else{
						newPath = StringUtils.replace(newPath, file.getName(), name);
					}
					success = true;
				}else{
					status_msg ="转化图像格式失败，源文件不存在！"; 
				}
			} catch (Exception e) {
				e.printStackTrace();
				status_msg = e.getMessage() ;
			}
		}else{
			status_msg = "转化图像格式失败，请设置要转换的目标图片格式！";
		}
		
		map.put(STATUS_CODE, success?AjaxResult.SUCCESS:AjaxResult.FAIL);
		map.put(MSG, status_msg);
		map.put(RESULT, newPath);
		String msg = this.sendJSONObject(response,map);
		this.logger.debug("将文件["+path+"]转化图像格式为["+format+"]:"+status_msg+":"+msg);
	
	}
	
	@Override
	public void down(HttpServletRequest request, HttpServletResponse response)
			throws ImageOperateException, ServletException, IOException {
		
		request.getRequestDispatcher("/fileDown").forward(request, response);
	}

	@Override
	public void upload(HttpServletRequest request, HttpServletResponse response)
			throws ImageOperateException, ServletException, IOException {
		
		request.getRequestDispatcher("/fileUpload").forward(request, response);
	}
	
	public void detect(HttpServletRequest request, HttpServletResponse response)throws ImageOperateException, ServletException, IOException{
			String path = PathUtil.getPath(request, this.baseDir);
			String destpath = PathUtil.getPath(request,this.baseDir,DEST_PARA);
			Map<String,Object> map = new HashMap<String,Object>(3);
			String status_msg = "识别成功！"; 
			boolean success =  false;
			String newPath = PathUtil.getPathPara(request);
			try {
				File file = new File(path);
				boolean hasDestPath = false;
				if(ObjectUtil.isEmpty(destpath)){
					hasDestPath = false;
				}
				if(file.exists()){
					String name = "";
					if(!hasDestPath){
						name = FileUtil.getFileNameWithoutExtension(file.getName())+"_detect_"+RandUtil.genDateYYYYMMDDHHmmName()+FileUtil.getExt(file);
						name = FileUtil.getFinalFileName(file.getParent(), name);
						destpath =  file.getParent() + File.separator + name;
					}
					File pfile = new File(destpath);
					String parent = pfile.getParent();
					File pfileDir = new File(parent);
					if(!pfileDir.exists()){
						pfileDir.mkdirs();
					}
					if(!pfile.exists()){
//						im.detect(path, destpath);
						if(!hasDestPath){
							newPath = StringUtils.replace(newPath, file.getName(), name);
						}else{
							newPath = PathUtil.getPathPara(request,DEST_PARA);
						}
						success = true;
					}else{
						status_msg ="识别失败，目标文件已存在，请重新设置目标文件！"; 
					}
				}else{
					status_msg ="识别失败，源文件不存在！"; 
				}
			} catch (Exception e) {
				e.printStackTrace();
				status_msg = e.getMessage() ;
			}
			
			map.put(STATUS_CODE, success?AjaxResult.SUCCESS:AjaxResult.FAIL);
			map.put(MSG, status_msg);
			map.put(RESULT, newPath);
			String msg = this.sendJSONObject(response,map);
			this.logger.debug("识别["+path+"]为["+destpath+"]:"+status_msg+":"+msg);
		
	}

	/**
     * 发送多个键值对json数据到页面
     * @author Defender
     * 2013-7-1 下午09:13:37
     * @param map
     * @return void
     */
    protected String sendJSONObject(final HttpServletResponse response,final Map<String,Object> map) {  
        JSONObject jsonObj = new JSONObject();
        jsonObj.putAll(map);
        return this.sendJsonData(response,jsonObj);
    } 
    
    
	/**
	 * 发送一个键值对json数据到页面
	 * @author Defender
	 * 2013-7-1 下午09:13:29
	 * @param objName
	 * @param obj
	 * @return void
	 */
    protected String sendJSONObject(final HttpServletResponse response,final String  objName, final Object obj) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(objName, obj); 
       return this.sendJsonData(response,jsonObj);
    }  
    


   /**
    * 发送json数据到页面
    * @author Defender
    * 2013-7-1 下午09:12:17
    * @param jsonObj
    * @return void
    */
    protected String sendJsonData(final HttpServletResponse response, final JSONObject jsonObj){
    	String encoding = "UTF-8";  
        String contentType = "application/json";  
        contentType = contentType + ";charset=" + encoding;  
        response.setContentType(contentType);  
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
        PrintWriter pw = null;
        String msg =jsonObj.toString();
		try {
			pw = response.getWriter();
			pw.write(msg);  
		    pw.flush();   
		} catch (IOException e) {
			this.logger.debug("sendJsonData:"+e.getMessage());
		}   
		return msg;
    }

	public String getBaseDir() {
		return baseDir;
	}

	public void setBaseDir(String baseDir) {
		this.baseDir = baseDir;
	}

	public boolean isAbsolutePath() {
		return isAbsolutePath;
	}

	public void setAbsolutePath(boolean isAbsolutePath) {
		this.isAbsolutePath = isAbsolutePath;
	}

	public String getContextDir() {
		return contextDir;
	}

	public void setContextDir(String contextDir) {
		this.contextDir = contextDir;
	}

}
